<template>
  <div class="flex">
    <div
      class="flex-none w-52 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900 rounded p-4"
       style="max-height: 80vh"
    >
      <div class="flex justify-between items-center">
        <span class="text font-bold">对话列表</span>
      </div>
      <el-scrollbar class="mt-4" style="height: calc(100vh - 300px)">
        <div
          v-for="chat in chatList"
          :key="chat.user_id"
          class="rounded flex justify-between items-center px-2 py-4 cursor-pointer mt-2 hover:bg-blue-50 dark:hover:bg-blue-900 bg-gray-50 dark:bg-gray-800 gap-4"
          :class="
            selectID === chat.user_id
              ? 'text-active'
              : 'text-slate-700 dark:text-slate-50'
          "
          @click="toDetail(chat)"
        >
          <img
            :src="chat.avatar || defaultAvatar"
            alt="头像"
            class="w-10 h-10 rounded-full mr-2"
          />
          <div class="flex-1">
            <div class="text-base font-semibold">
              {{ chat.username || "未设置" }}
            </div>
            <div class="text-sm text-gray-500 dark:text-gray-400">
              {{ chat.phone || "未设置" }}
            </div>
            <div class="text-xs text-gray-400 dark:text-gray-500">
              {{ chat.message || "无内容" }}
            </div>
            <div class="text-xs text-gray-400 dark:text-gray-500">
              {{ chat.timestamp || "无时间" }}
            </div>
          </div>
          <!-- 显示未读消息计数 -->
          <div
            v-if="chat.unread_count > 0"
            class="text-xs bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center"
          >
            {{ chat.unread_count }}
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div
      v-if="selectID"
      style="max-height: 80vh"
      class="flex-1 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900"
    >
      <!-- 监听 newMessage 事件 -->
      <ChatDetail :chat-id="selectID" @newMessage="updateChatList" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { connectListWebSocket, closeDetailWebSocket } from "@/utils/websocket";
import ChatDetail from "@/view/connect/chatDetail.vue";

defineOptions({ name: "ChatList" });

const userId = 1;
const defaultAvatar = "../../../public/logo.png";
const selectID = ref(null);
const chatList = ref([]);

const toDetail = (chat) => {
  selectID.value = chat.user_id;
  // 选中后将未读消息数重置为 0
  const selectedChat = chatList.value.find(
    (item) => item.user_id === chat.user_id
  );
  if (selectedChat) {
    selectedChat.unread_count = 0;
  }
};

// 处理新消息并更新 chatList
const updateChatList = (msg) => {
  const { sender_id, content, timestamp } = msg;
  const formattedTime = timestamp || "无时间";

  // 查找 sender_id 是否在 chatList 中存在
  const existingChatIndex = chatList.value.findIndex(
    (chat) => chat.user_id === sender_id
  );

  // 如果存在则更新内容和时间戳
  if (existingChatIndex !== -1) {
    chatList.value[existingChatIndex].message = content || "无内容";
    chatList.value[existingChatIndex].timestamp = formattedTime;
  }
};

const handleReceiveListMessage = (msg) => {
  const { sender_id, content, timestamp } = JSON.parse(msg.message || "{}");
  const { avatar, nickname, phone, username } = msg.user || {};

  // 将时间戳转换为标准时间格式
  const formattedTime = timestamp
    ? new Date(timestamp).toLocaleString() // 转换成本地标准时间格式
    : "无时间";

  const existingChatIndex = chatList.value.findIndex(
    (chat) => chat.user_id === sender_id
  );

  if (existingChatIndex !== -1) {
    chatList.value[existingChatIndex].message = content || "无内容";
    chatList.value[existingChatIndex].timestamp = formattedTime;
    chatList.value[existingChatIndex].unread_count =
      chatList.value[existingChatIndex].unread_count + 1;
  } else {
    chatList.value.push({
      user_id: sender_id,
      username: username || nickname || "未设置",
      phone: phone || "未设置",
      avatar: import.meta.env.VITE_BASE_API + avatar || defaultAvatar,
      message: content || "无内容",
      timestamp: formattedTime,
      unread_count: msg.unread_count || 0, // 初始化未读消息数
    });
  }
};

onMounted(() => {
  connectListWebSocket(userId, handleReceiveListMessage);
});

onBeforeUnmount(() => {
  closeDetailWebSocket();
});
</script>

<style scoped>
.active {
  background-color: var(--el-color-primary) !important;
  color: #fff;
}
</style>
